import { stringify } from 'qs';
import { omitBy, isUndefined } from 'lodash';

import { getMd5, getToken, request } from '@/utils';
import { fingerprintFetch } from '@/utils/request';

export const fetchData = async ({ current, pageSize }, formData: any) => {
  if (formData.rangeTime) {
    formData.startDate = formData.rangeTime[0].format('YYYY-MM-DD');
    formData.endDate = formData.rangeTime[1].format('YYYY-MM-DD');
    delete formData.rangeTime;
  }

  if (formData.vehicleType && Array.isArray(formData.vehicleType)) {
    const [_, vehicleType] = formData.vehicleType;
    formData.vehicleType = vehicleType;
  }

  const result = await request(
    `/feedback/exception/log/page?${stringify(
      omitBy({ size: pageSize, page: current, ...formData }, isUndefined),
    )}`,
  );

  return {
    list: result.data?.list || [],
    total: result.data?.pagination.total || 0,
  };
};

export const fetchBrand = async () => {
  const result = await request('/common/vehicle/getcurrentbrand');

  if (result.statusCode !== '0') return [];

  return result.data;
};

export const fetchSeries = async (brandId: string) => {
  // getserieslist gettypelist
  const result = await request('/common/vehicle/gettypelist?brandId=' + brandId);

  if (result.statusCode !== '0') return [];

  return result.data;
};

export const fetchVersion = async () => {
  const result = await request('/feedback/log/version/list');

  if (result.statusCode !== '0') return [];

  return result.data;
};

export const fetchFileUrl = async (fileUuid: string) => {
  const url = `${window.g.url}/presign/downloadurl`;

  const result = await (
    await fingerprintFetch(url, {
      method: 'POST',
      body: JSON.stringify({
        fileUuid,
      }),
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        OptAuthorization: `${getToken()}`,
        shaSign: getMd5(
          JSON.stringify({
            fileUuid,
          }),
        ),
      },
    })
  ).json();

  if (result?.data?.presignDownloadUrl) {
    window.open(result.data.presignDownloadUrl, '_self');
  }
};
